home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Tech Arsenal 1
/
Tech Arsenal (Arsenal Computer).ISO
/
tek-01
/
lcppb.zip
/
LCPP04.ZIP
/
SWAP.CPP
< prev
next >
Wrap
C/C++ Source or Header
|
1991-07-04
|
2KB
|
74 lines
// swap.cpp -- Use pointers to swap any two same-size variables
//#include <stream.hpp>
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
struct rec { // Sample structure to swap
char *title;
char *author;
int pages;
};
/* -- Function prototypes */
void swapbytes(void *p1, void *p2, unsigned size);
void showrecs(char *s);
rec r1, r2; // Two rec global variables
main()
{
/* -- Assign test values to the global variables */
r1.title = "The C++ Programming Language";
r1.author= "Bjarne Stroustrup";
r1.pages = 328;
r2.title = "Mastering Turbo Pascal 5.5";
r2.author= "Tom Swan";
r2.pages = 877;
/* -- Display variables before and after swapping */
showrecs("Before");
swapbytes(&r1, &r2, sizeof(r1));
showrecs("After");
}
/* -- Swap size bytes addressed by p1 and p2 */
void swapbytes(void *p1, void *p2, unsigned size)
{
unsigned char t; // Temporary place to hold each byte
while (size-- > 0) {
t = *(char *)p1;
*((char *)p1)++ = *(char *)p2;
*((char *)p2)++ = t;
}
}
/* -- Display values of r1 and r2 */
void showrecs(char *s)
{
cout << "\n\n" << s << "\n============";
cout << "\nr1.title = " << (r1.title);
cout << "\nr1.author = " << (r1.author);
cout << "\nr1.pages = " << (r1.pages);
cout << "\n\nr2.title = " << (r2.title);
cout << "\nr2.author = " << (r2.author);
cout << "\nr2.pages = " << (r2.pages) << '\n';
}
// Copyright (c) 1990 by Tom Swan. All rights reserved
// Revision 1.00 Date: 08/30/1990 Time: 07:37 am
// Revision 1.01 Date: 07/03/1991 Time: 04:00 pm
// Converted for Borland C++ 2.0